# -*- encoding: utf-8 -*-
"""
File Name: severity_classify.py
Description:
Author : 'lirui'
date: 2024/11/4
Contact: marjey_lee@163.com
Change Activity:
2024/11/4:
"""
from modules.blk.cmdb.cmdb_service import CMDBService
from projects.monitoring.common.do.alarm import Alarm
from projects.monitoring.common.utils.redis_keys_util import RedisKeysUtil


class AlarmsSeverityClassifier:
    def __init__(self):
        self.cmdb_data = self._load_cmdb_data()

    @staticmethod
    def _load_cmdb_data():
        data = CMDBService().select('alarm_classification')
        lst = data['data']['info']
        mapping = {}
        for item in lst:
            k = item['alarm_type']
            if k not in mapping:
                mapping[k] = []
            mapping[k].append(item)
        return mapping

    def classify_alarm(self, alarm: Alarm):
        """

        Args:

            alarm:
        Returns:

        """
        if alarm.alarm_source == RedisKeysUtil.get_internal_zabbix_publisher_keys():
            return self._classify_zabbix(alarm)
        if alarm.alarm_source == RedisKeysUtil.get_spider_monitor_publisher_keys():
            return self._classify_spider_alarm(alarm)
        return alarm

    def classify_alarms(self, alarms: list[Alarm]):
        format_alarms = []
        for a in alarms:
            a = self.classify_alarm(a)
            format_alarms.append(a)
        return format_alarms

    def _classify_spider_alarm(self, p: Alarm):
        for criterion in self.cmdb_data['spider']:
            if criterion['ignore_monitor_item_name'] and criterion['regex_string'] in p.alarm_info:
                p.severity = criterion['classification']
                return p
            else:
                if p.hostname == criterion['monitor_item_name'] and criterion['regex_string'] in p.alarm_info:
                    p.severity = criterion['classification']
                    return p
        return p

    def _classify_zabbix(self, alarm: Alarm):
        for criterion in self.cmdb_data['zabbix']:
            if criterion['ignore_monitor_item_name'] and criterion['regex_string'] in alarm.alarm_info:
                alarm.severity = criterion['classification']
                return alarm
            else:
                if alarm.hostname == criterion['monitor_item_name'] and criterion['regex_string'] in alarm.alarm_info:
                    alarm.severity = criterion['classification']
                    return alarm
        return alarm
